<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 文件相关Controller v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\controller;

use app\core\model\SiteConfig;
use app\core\service\UploadService;
use Qiniu\Auth;

class FileController extends CoreBaseController {

    /**
     * 文件上传
     */
    public function upload() {
        $responseType = input("get.responseType");

        $saveFile = UploadService::save(request()->file("file"));
        if ($saveFile instanceof \think\File) {
            $fileUrl = $saveFile->getInfo("fileUrl");
            if ($responseType == 'layedit') {
                return json([
                    'code' => 0,
                    'msg' => '上传成功',
                    'data' => [
                        'src' => $fileUrl,
                        'title' => $saveFile->getInfo("name")
                    ]
                ]);
            }
            $this->success("上传成功", null, ['fileUrl' => $fileUrl]);
        } else {
            if ($responseType == 'layedit') {
                return json([
                    'code' => -1,
                    'msg' => "文件上传失败" . ($saveFile ? ":" . $saveFile : ""),
                ]);
            }
            // 上传失败获取错误信息
            $this->error("文件上传失败" . ($saveFile ? ":" . $saveFile : ""));
        }
    }

    /**
     * 获取七牛云存储上传token
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getQiniuUploadToken() {
        //TODO 改成EnterpriseSiteConfig
        $accessKey = SiteConfig::get("qiniuAK");
        $secretKey = SiteConfig::get("qiniuSK");
        $bucket = SiteConfig::get("qiniuBucket");

        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);

        return json([
            "uptoken" => $token
        ]);
    }
}
